package com.jiyu.controller;

import com.jiyu.pojo.Book;
import com.jiyu.service.BookService;
import com.jiyu.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@RestController
public class LibraryController {
    @Autowired
    BookService bookService;

    @GetMapping("/api/books")
    public List<Book> list() throws Exception {
        return bookService.list();
    }

    @PostMapping("/api/admin/books")
    public Book addOrUpdate(@RequestBody Book book) throws Exception {
        bookService.addOrUpdate(book);
        return book;
    }

    @PostMapping("/api/admin/delete")
    public void delete(@RequestBody Book book) throws Exception {
        bookService.deleteById(book.getId());
    }


    @GetMapping("/api/categories/{cid}/books")
    public List<Book> listByCategory(@PathVariable("cid") int cid) throws Exception {
        if (0 != cid) {
            return bookService.listByCategory(cid);//查询一类
        } else {
            return list();//查询所有
        }
    }

    @GetMapping("/api/search")
    public List<Book> searchResult(@RequestParam("keywords") String keywords) {
        // 关键词为空时查询出所有书籍
        if ("".equals(keywords)) {
            return bookService.list();
        } else {
            return bookService.Search(keywords);
        }
    }

    //对接收到的文件重命名（避免重名），但保留原始的格式。可以进一步做一下压缩，或者校验前端传来的数据是否为指定格式
    @PostMapping("api/covers")
    public String coversUpload(MultipartFile file){
        System.out.println("文件上传中");

        String folder = "D:/test";
        File imageFolder = new File(folder);
        //后缀名（最后四位）
        String suffix=file.getOriginalFilename().substring(file.getOriginalFilename().length() - 4);

        //设置日期格式
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
        // new Date()为获取当前系统时间
        String format = df.format(new Date());
        String newSuffix="-"+ format + suffix;

        //图片名后加上当前日期，防止随机数也重复
        File f = new File(imageFolder, StringUtils.getRandomString(6)+newSuffix);
        if (!f.getParentFile().exists())
            f.getParentFile().mkdirs();
        try {
            file.transferTo(f);
            String imgURL = "http://localhost:8443/api/file/" + f.getName();//虚拟路径 实际是D:/test
            return imgURL;
        } catch (Exception e) {
            e.printStackTrace();
            return "false";
        }
    }

}